// pages/payfor/index.js
var PayTotalPrice = 0;
var OrderTicketID = '';
var order = "";
var coupons = "";
var hasChooseSeat = [];
var plandate = '';
var showdate = '';
var cinema = '';
var ticketprice = 0;
var GoodsInfo = '';
var reqPaySign = '';
var reqSaveOrderSign = '';
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var strAppCode = config.SmallApp;
var lingshilist = "";
var GoodsInfo = "";
var paymethod = "";
var app = getApp();
var cardlist = []
var strCardNo = '';




/** 
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
 */

// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数
var total_micro_second = 5 * 60 * 1000;

/* 毫秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: date_format(total_micro_second)
  });

  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止",
      issuccess: false,
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 10;
    count_down(that);
  }
    , 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  return min + "分" + sec + "秒";
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clock: '',//支付剩余时间
    year: '',//当前的年份
    chkzuolist: [],//选择的座位
    chkzuo: '',//选择的座位
    payforprice: 0,//付钱价格
    piaoprice: 0,//票价格
    tingnum: 0,//电影厅号
    dyid: 0,//电影id
    dyname: '',//电影名称
    yyid: 0, //影院id
    yyname: '', //影院名称
    chkday: '',//日期
    changciid: '',//场次id
    time: '',//开场时间
    lingshilist: [],//零食列表
    zhifuqian: 0,//支付的钱
    open: false,//列表选项
    items: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // //TODO 记得注释掉
    //     app.globalData.loginuserinfo.mobile ="15765508953"

    coupons = options.coupons;
    console.log(options)

    GoodsInfo = ""
    if (lingshilist !== '') {
      for (var i = 0; i < lingshilist.length; i++) {
        if (lingshilist[i].buynum > 0) {
          GoodsInfo += lingshilist[i].GoodsID + "," + lingshilist[i].buynum + "|"
        }
      }
      GoodsInfo = GoodsInfo.substring(0, GoodsInfo.length - 1)
    }

    PayTotalPrice = options.PayTotalPrice;//支付价格

    order = JSON.parse(options.order)
    OrderTicketID = order.OrderTicketID; //订单号
    lingshilist = JSON.parse(options.lingshilist);
    hasChooseSeat = JSON.parse(options.hasChooseSeat);
    plandate = JSON.parse(options.plandate);
    console.log(plandate)
    showdate = options.showdate;
    cinema = options.cinema;
    console.log(cinema)
    ticketprice = options.ticketprice;
    var that = this;
    var chkzuo = "";
    for (var i = 0; i < hasChooseSeat.length; i++) {
      chkzuo += hasChooseSeat[i].SeatRow + "排" + hasChooseSeat[i].SeatCol + "座,"

    }
    //去除最后一个逗号
    chkzuo = chkzuo.substr(0, chkzuo.length - 1);

    that.setData({
      orderno: JSON.parse(options.order).OrderNo,
      piaoprice: ticketprice,//票价
      payforprice: PayTotalPrice,//付钱价格
      tingnum: plandate.HallName,//电影厅号
      // dyid: options.dyid,//电影id
      dyname: plandate.FilmName,//电影名称
      // yyid: options.yyid, //影院id
      yyname: plandate.CinemaName, //影院名称
      chkday: showdate,//日期
      time: plandate.PlayStartTime,//开场时间
      chkzuolist: hasChooseSeat,//选择的座位
      year: new Date().getFullYear(),//得到年份
      chkzuo: chkzuo,
      zhifuqian: PayTotalPrice,//支付的钱
    })

    //计时器
    count_down(this);
    //TODO请求会员卡 
    // return req.
    return req.CardList(app.globalData.token).then(res => {
      console.log(res)
      cardlist = res.data.data;
      console.log(cardlist);
      if (cardlist.length > 0) {
        this.setData({ hascard: true })
        paymethod = 0;
        for (var i = 0; i < cardlist.length; i++) {
          cardlist[i].cardNostart = cardlist[i].Mcode.substring(0, 4) + "****" + cardlist[i].Mcode.substr(cardlist[i].Mcode.length - 2, cardlist[i].Mcode.length)
        }
        if (coupons.length > 0 && PayTotalPrice === 0) {
          //就展示0呗
        } else if (PayTotalPrice > 0) {
          //先展示会员价
          var couarr = "";
          if (coupons == "") {
            couarr = 0;
          } else {
            couarr = coupons.split(",").length

          }

          PayTotalPrice = (hasChooseSeat.length - couarr) * plandate.mPriceLowest;
          console.log(PayTotalPrice)
        }
      }

      this.setData({ cardlist: cardlist, payforprice: PayTotalPrice })
    })

    //结束标识符
  },
  /**零食的数量的加**/
  addnum: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    //重置数据
    var lingshilist = that.data.lingshilist;
    var txtarray = [];

    for (var i = 0; i < lingshilist.length; i++) {
      if (id == lingshilist[i].id) {
        txtarray[i] = {
          id: lingshilist[i].id,
          imgpath: lingshilist[i].imgpath,
          geren: lingshilist[i].geren,
          name: lingshilist[i].name,
          istuijian: lingshilist[i].istuijian,
          tejia: lingshilist[i].tejia,
          pujia: lingshilist[i].pujia,
          buynum: lingshilist[i].buynum + 1
        };
      } else {
        txtarray[i] = {
          id: lingshilist[i].id,
          imgpath: lingshilist[i].imgpath,
          geren: lingshilist[i].geren,
          name: lingshilist[i].name,
          istuijian: lingshilist[i].istuijian,
          tejia: lingshilist[i].tejia,
          pujia: lingshilist[i].pujia,
          buynum: lingshilist[i].buynum
        };
      }
    }
    //重置后的数据

    var lingshiqian = 0;
    for (var j = 0; j < txtarray.length; j++) {
      if (txtarray[j].buynum > 0) {
        lingshiqian += txtarray[j].buynum + txtarray[j].tejia;
      }
    }
    //计算最后的总价
    var zhifuqian = parseFloat(that.data.payforprice) + lingshiqian;
    //赋值
    that.setData({
      lingshilist: txtarray,
      zhifuqian: zhifuqian.toFixed(2)
    })
    //结束标识符
  },
  /**减少购买零食**/
  jiannum: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    //重置数据
    var lingshilist = that.data.lingshilist;
    var txtarray = [];

    for (var i = 0; i < lingshilist.length; i++) {
      if (id == lingshilist[i].id) {
        txtarray[i] = {
          id: lingshilist[i].id,
          imgpath: lingshilist[i].imgpath,
          geren: lingshilist[i].geren,
          name: lingshilist[i].name,
          istuijian: lingshilist[i].istuijian,
          tejia: lingshilist[i].tejia,
          pujia: lingshilist[i].pujia,
          buynum: lingshilist[i].buynum - 1 <= 0 ? 0 : lingshilist[i].buynum - 1
        };
      } else {
        txtarray[i] = {
          id: lingshilist[i].id,
          imgpath: lingshilist[i].imgpath,
          geren: lingshilist[i].geren,
          name: lingshilist[i].name,
          istuijian: lingshilist[i].istuijian,
          tejia: lingshilist[i].tejia,
          pujia: lingshilist[i].pujia,
          buynum: lingshilist[i].buynum
        };
      }
    }
    //重置后的数据

    var lingshiqian = 0;
    for (var j = 0; j < txtarray.length; j++) {
      if (txtarray[j].buynum > 0) {
        lingshiqian += txtarray[j].buynum + txtarray[j].tejia;
      }
    }
    //计算最后的总价
    var zhifuqian = parseFloat(that.data.payforprice) + lingshiqian;
    //赋值
    that.setData({
      lingshilist: txtarray,
      zhifuqian: zhifuqian.toFixed(2)
    })
  },
  /**订单详情页**/
  order_detail: function () {
    var that = this;


    //没卖品 直接支付
    if (paymethod === '') {
      wx.showModal({
        title: '提示',
        content: '请选择支付方式',
      })
    } else if (paymethod == 'wxpay') {
      //TODO 微信支付
      if (coupons == "") {
        ticketprice = hasChooseSeat.length * plandate.pricesale1;
      } else {
        var conponsarr = coupons.split(",");
        if (conponsarr.length < hasChooseSeat.length) {
          //选的卷 比选的座少
          ticketprice = (hasChooseSeat.length - conponsarr.length) * plandate.pricesale1
        } else if (conponsarr.length == hasChooseSeat.length) {
          //支付0元钱
          var paysign = "strAppCode=" + strAppCode + "OrderTicketID=" + OrderTicketID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "pamounts=" + ticketprice + "" + "coupons=" + coupons + "";
          return req.GetSignStr(paysign).then(res => {
            if (res.data.success) {
              reqPaySign = res.data.data;
            }
          }).then(() => {
            return req.SellTicketB(strAppCode, OrderTicketID, "ooORTwu9F9-roa7PI74rHIWfjuvA", app.globalData.loginuserinfo.mobile, app.globalData.loginuserinfo.mobile, "0", coupons, reqPaySign, app.globalData.token)
          }).then(res => {
            console.log(res)
            var result = res.data.data
            if (res.data.success) {
              setTimeout(function () {
                // 放在最后--
                wx.hideLoading();
              }
                , 1000)

              wx.showToast({
                title: '支付成功',
                success: function () {
                  setTimeout(function () {
                    // 放在最后--
                    wx.redirectTo({
                      url: '../payfor/detail?PayTotalPrice=' + 0 + '&&order=' + JSON.stringify(order) + '&&coupons=' + coupons + '' + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&ticketprice=' + 0 + '&&lingshilist=' + JSON.stringify(lingshilist) + '&&result=' + JSON.stringify(result)
                    })
                  }
                    , 3000)
                }
              })

            } else {
              wx.showModal({
                title: '提示',
                content: '支付失败',
              })
              setTimeout(function () {
                // 放在最后--
                wx.hideLoading();
              }
                , 1600)
              return false;
            }
          })
        } else {
          //异常支付
          wx.showModal({
            title: '提示',
            content: '您的支付有异常',
          })
          return false
        }

      }

      var paysign = "strAppCode=" + strAppCode + "OrderTicketID=" + OrderTicketID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "pamounts=" + ticketprice + "" + "coupons=" + coupons + "";
      return req.GetSignStr(paysign).then(res => {
        if (res.data.success) {
          reqPaySign = res.data.data;

        }
      }).then(() => {
        return req.GetMiniAppPaySign(strAppCode, OrderTicketID, "ooORTwu9F9-roa7PI74rHIWfjuvA", app.globalData.loginuserinfo.mobile, app.globalData.loginuserinfo.mobile, ticketprice, coupons, reqPaySign, app.globalData.token).then(res => {

          console.log(res)
          var pay = res.data
          //发起支付   
          var timeStamp = pay.TimeStamp;
          console.log("timeStamp:" + timeStamp)
          var packages = pay.Package;
          console.log("package:" + packages)
          var nonceStr = pay.NonceStr;
          console.log("nonceStr:" + nonceStr)
          var paySign = pay.PaySign;
          console.log("paySign:" + paySign)
          var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
          //调用支付
          // pay(param)
          console.log("支付")
          wx.requestPayment({
            timeStamp: param.timeStamp,
            nonceStr: param.nonceStr,
            package: param.package,
            signType: param.signType,
            paySign: param.paySign,
            success: function (res) {
              // 业务逻辑
              console.log("支付成功")
              wx.showToast({
                title: '支付成功',
                success: function () {
                  setTimeout(function () {
                    // 放在最后--
                    wx.redirectTo({
                      url: '../payfor/detail?PayTotalPrice=' + PayTotalPrice + '&&order=' + JSON.stringify(order) + '&&coupons=' + coupons + '' + ticketprice + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&ticketprice=' + ticketprice + '&&lingshilist=' + JSON.stringify(lingshilist)
                    })
                  }
                    , 3000)
                }
              })


            }, fail: function (error) {
              console.log(error)

            }
          })
        })
      })


    }
    else {  //TODO 会员卡支付
      wx.showLoading({
        title: '支付中',
        mask: true
      })
      // PriceMember
      if (coupons == "") {
        ticketprice = hasChooseSeat.length * plandate.mPriceLowest
      } else {
        var conponsarr = coupons.split(",");
        ticketprice = (hasChooseSeat.length - conponsarr.length) * plandate.mPriceLowest
      }
      console.log(cardlist)
      strCardNo = cardlist[paymethod].Mcode;
      if (ticketprice > cardlist[paymethod].Balance){
        wx.showModal({
          title: '提示',
          content: '卡内余额不足',
        })
        wx.hideLoading();
        return false;
      }
      var paysign = "strAppCode=" + strAppCode + "OrderTicketID=" + OrderTicketID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "strCardNo=" + strCardNo + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "coupons=" + coupons + "" + "PayTotalPrice=" + ticketprice;
      return req.GetSignStr(paysign).then(res => {
        if (res.data.success) {
          reqPaySign = res.data.data;
        }
      }).then(() => {
        // 发起支付
        return req.SellTicketA(strAppCode, OrderTicketID, "ooORTwu9F9-roa7PI74rHIWfjuvA", app.globalData.loginuserinfo.mobile, strCardNo, app.globalData.loginuserinfo.mobile, coupons, ticketprice, reqPaySign, app.globalData.token).then(res => {
          console.log(res)
          var result = res.data.data
          // if (res.data.success) {
          //跳转到支付成功页面
          if (res.data.success) {
            setTimeout(function () {
              // 放在最后--
              wx.hideLoading();
            }
              , 1000)

            wx.showToast({
              title: '支付成功',
              success: function () {
                setTimeout(function () {
                  // 放在最后--
                  wx.redirectTo({
                    url: '../payfor/detail?PayTotalPrice=' + PayTotalPrice + '&&order=' + JSON.stringify(order) + '&&coupons=' + coupons + '' + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&ticketprice=' + ticketprice + '&&lingshilist=' + JSON.stringify(lingshilist) + '&&result=' + JSON.stringify(result)
                  })
                }
                  , 3000)
              }
            })

          } else {
            wx.showModal({
              title: '提示',
              content: '会员卡支付失败',
            })
            setTimeout(function () {
              // 放在最后--
              wx.hideLoading();
            }
              , 1600)
            return false;
          }

        })
      })
    }

    // }




  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  showitem: function () {
    this.setData({
      open: !this.data.open
    })
  },
  showitem2: function () {
    this.setData({
      open2: !this.data.open
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  radioChange: function (e) {
    console.log(e)
    paymethod = e.detail.value;
    var conponsarr ="";
    if (coupons ==""){
      conponsarr =0;
    }else{
      conponsarr = coupons.split(",").length
    }
    if (e.detail.value === "") {
      ticketprice = (hasChooseSeat.length - conponsarr) * plandate.pricesale1
    }
    else if (e.detail.value == "wxpay") {
  
      ticketprice = (hasChooseSeat.length - conponsarr) * plandate.pricesale1
    }
    else {
      ticketprice = (hasChooseSeat.length - conponsarr) * plandate.mPriceLowest
    }
    console.log(ticketprice)
    this.setData({ payforprice:ticketprice })
  }
 
})